package com.kylin.common.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;

import org.apache.struts.taglib.html.SelectTag;

import com.kylin.common.Constants;
import com.kylin.common.entity.SelectOption;

public class DictSelectTag extends SelectTag {
	protected String dictName;

	public String getDictName() {
		return dictName;
	}

	public void setDictName(String dictName) {
		this.dictName = dictName;
	}

	public int doStartTag() throws JspException {
		int rs = super.doStartTag();
        pageContext.setAttribute("taglib.html.DICT_SELECT", this);
		try {
			pageContext.getOut().println();
			pageContext.getOut().println(getOptions());
			pageContext.getOut().println();
		} catch (IOException e) {
			throw new JspException(e);
		}
		return rs;
	}



    private String getOptions() {
		StringBuffer sb = new StringBuffer("<option/>\n");
		if (this.dictName == null
				|| !(Constants.dictionarys.get(dictName) instanceof SelectOption[]) ) {
			return "<option/>\n";
		}

		SelectOption[] options = (SelectOption[]) Constants.dictionarys.get(dictName);
		for (int i = 0; i < options.length; i++) {
			sb.append("<option value=");
			sb.append("\"").append(options[i].getValue()).append("\"");
			if(this.matchValue(options[i].getValue()))
				sb.append(" selected=\"true\"");
			sb.append(" >");
			sb.append(options[i].getText());
			sb.append("</option>\n");
		}
		return sb.toString();
	}

    private boolean matchValue(String v){
    	if(this.match == null || this.match.length ==0)
    		return false;
    	for(int i =0;i<this.match.length;i++){
    		if(match[i]!= null)
    			if(match[i].equals(v))
    				return true;
    	}
    	return false;
    }
}
